package com.example.javaow.controller;/*
 * @Auther:Sadie
 * @Date:2025/8/5
 * @Description:
 * @VERSON:1.8
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;

import com.example.javaow.domain.base.BatchResult1;
import com.example.javaow.domain.base.BatchResultEntry;
import com.example.javaow.domain.base.CtwEntity;
import com.example.javaow.domain.base.ResponseResult;
import com.example.javaow.domain.dto.OWDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ctwow")
@RequiredArgsConstructor
@Slf4j
public class OpenWinController {
    @Autowired
    private CtwEntity ctwEntity;
    @PostMapping("/valves")
    public ResponseResult batchSend(@RequestBody List<OWDto> messages) {
        List<BatchResultEntry> results = new ArrayList<>();
        // 遍历每个指令，收集结果
        for (OWDto msg : messages) {
            ResponseResult singleResult = send(msg);
            // 将结果封装为 BatchResultEntry
            BatchResultEntry entry = new BatchResultEntry(
                    msg.getDeviceAddressBB().toString(), // 设备ID
                    singleResult.getCode(), // 状态码
                    singleResult.getMsg(),  // 消息描述
                    singleResult.getCode() == 200 // 是否成功
            );
            results.add(entry);
        }

        // 构建最终响应
        return ResponseResult.success(new BatchResult1(results));
    }
    public ResponseResult send(@RequestBody OWDto msg) {
        log.info("向测控一体化阀门发送消息：{}", msg);
        Boolean flag = false;
        // 构建客户端信息
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(ctwEntity.getAppKey())
                .appSecret(ctwEntity.getAppSecret())
                .build();
        CreateCommandRequest request = new CreateCommandRequest();
        String masterKey = ctwEntity.getMasterKey();
        request.setParamMasterKey(masterKey);
        //获取dtuid
        String deviceId;
        if(msg.getDtuId() == null){
            deviceId= "172044834";
        }
        else {deviceId= msg.getDtuId();}
        // 获取开窗时间
        Integer openWindowTime = msg.getOpenWindowTime();
        //获取设备地址/分组地址
        Integer groupAddressAA = msg.getGroupAddressAA();
        Integer deviceAddressBB = msg.getDeviceAddressBB();
        //构建指令
        //01000010 00000010 00000001 00001100
        //定义一个二进制类型接收
        StringBuilder binaryData = new StringBuilder();
        //开头0100固定
        binaryData.append("0100");
        //AA低四位为分组地址转为2进制
        String binaryStringAA = String.format("%4s", Integer.toBinaryString(groupAddressAA & 0x0F)).replace(' ', '0');

        StringBuilder append = binaryData.append(binaryStringAA);
        //不足4位前面补0

        log.info("指令数据：{}", append);
        //BB八位为设备地址转为2进制
        // BB八位为设备地址转为2进制，不足8位前面补0
        String binaryStringBB = String.format("%8s", Integer.toBinaryString(deviceAddressBB)).replace(' ', '0');
        binaryData.append(binaryStringBB);
        //CC默认
        if(msg.getRegisterSettingCC()!=null){
            binaryData.append(String.format("%8s", Integer.toBinaryString(msg.getRegisterSettingCC())).replace(' ', '0'));
        }
        else {
            binaryData.append("00000001");
        }

        //DD作为开窗时间转为2进制
        String binaryStringDD = String.format("%8s", Integer.toBinaryString(openWindowTime)).replace(' ', '0');

        binaryData.append(binaryStringDD);
        String fullData = binaryData.toString();
        log.info("指令数据：{}", fullData);
        //每8位一组进行累加和计算
        // 每8位一组进行累加和计算
        int sum = 0;
        for (int i = 0; i < fullData.length(); i += 8) {
            String substring = fullData.substring(i, i + 8);
            sum += Integer.parseInt(substring, 2);
        }
        //转为16进制只保留低八位
        // 只保留低八位（去掉进位）
        int checksum = sum & 0xFF;
        // 将校验和的二进制添加到完整数据末尾
        String checksumBinary = String.format("%8s", Integer.toBinaryString(checksum)).replace(' ', '0');
        binaryData.append(checksumBinary);
        //binaryData二进制转为16进制
        //String hexData = Integer.toHexString(checksum);
        String fullBinaryData = binaryData.toString();

        String hexData = binaryToHex(fullBinaryData);
        log.info("完整二进制指令数据：{}", fullBinaryData);
        log.info("完整16进制指令数据：{}", hexData);
        //保存到数据库中


        // 构建请求体
        JSONObject jsonObject = new JSONObject();
        //ctwing中的设备id当前代表的是集中器的id，在ctwing平台中是设备的id
        jsonObject.put("deviceId", deviceId);
        //发送者名称
        jsonObject.put("operator", "ceebic_test");
        jsonObject.put("productId", ctwEntity.getProductId());
        jsonObject.put("level", 1);
        jsonObject.put("ttl", 864000);
        JSONObject content = new JSONObject();
        //1：字符串  2：十六进制
        content.put("dataType", 2);
        content.put("payload", hexData);

        jsonObject.put("content", content);

        // 设置请求体
        request.setBody(jsonObject.toString().getBytes());

        CreateCommandResponse response = null;
        try {
            // 发送请求
            response = client.CreateCommand(request);
        } catch (Exception e) {
            // 处理异常
            log.error("发送指令时发生异常", e);
            return ResponseResult.error(-1, "发送指令时发生异常");
        }

        // 处理响应
        String message = new String(response.getBody());
        // 解析响应体
        JSONObject object = JSON.parseObject(message);
        System.out.println(object);
        Object o = object.get("code");
        String o1 = (String) object.get("msg");
        int o2 = (int) o;
        //传入设备id，发送指令，回复数据，当前用户名
        //String username = SecurityUtils.getCurrentUsername();
        // 解析result对象
        JSONObject result = object.getJSONObject("result");
        //解析响应体的指令id
        String commandId = "0";
        //解析响应体的产品id和设备id
        Integer productId = 0;
        String deviceId1 = "0";
        // 如果code为0则表示发送成功
        if (object.containsKey("code") && Integer.parseInt(o.toString()) == 0) {
            flag = true;
            //解析响应体的指令id
            commandId = result.getString("commandId");
            //解析响应体的产品id和设备id
            productId = result.getInteger("productId");
            deviceId1 = result.getString("deviceId");
        }
        //保存发送指令 分组 设备地址 发送时间 发送数据 响应结果
        //ctwingService.addMessage(msg.getDeviceAddressBB(), hexData,o1,username,flag,commandId,productId,deviceId,masterKey);
        if (!flag) {
            return ResponseResult.error(msg.getDeviceAddressBB().toString(),o2, o1);
        }
        //需要返回的设备地址deviceAddress
        client.shutdown();
        return ResponseResult.successs(msg.getDeviceAddressBB().toString(),o1);
    }

    /**
     * 将二进制字符串转换为十六进制字符串
     * @param binary 二进制字符串
     * @return 十六进制字符串
     */
    private String binaryToHex(String binary) {
        StringBuilder hex = new StringBuilder();
        // 确保二进制字符串长度是4的倍数，不足则在前面补0
        while (binary.length() % 4 != 0) {
            binary = "0" + binary;
        }
        // 每4位二进制转换为1位十六进制
        for (int i = 0; i < binary.length(); i += 4) {
            String fourBits = binary.substring(i, i + 4);
            int decimal = Integer.parseInt(fourBits, 2);
            hex.append(Integer.toHexString(decimal).toUpperCase());
        }
        return hex.toString();
    }



}
